<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { ref, watch, onBeforeUnmount, shallowRef } from "vue";
import { message } from "@/utils/message";
import { FormInstance } from "element-plus";
import { addOrUpdateBanner } from "@/api/sysbanner";
import { uploadImage, uploadVideo } from "@/api/sysupload";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => {
      return {};
    }
  }
});

const ruleFormRef = ref<FormInstance>();

const formVisible = ref(false);
const formData = ref(props.data);
const fileList = ref([]);

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      addOrUpdateBanner(formData.value)
        .then(res => {
          if (res.success) {
            message("提交成功", { type: "success" });
            formVisible.value = false;
            resetForm(formEl);
            emit("add-up-search"); //用emit来进行事件通知传递
          } else {
            message("提交失败:" + res.errMsg, { type: "error" });
          }
        })
        .catch(error => {
          message("提交失败:" + JSON.stringify(error), { type: "error" });
        });
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const closeDialog = () => {
  formVisible.value = false;
  resetForm(ruleFormRef.value);
};

const emit = defineEmits(["update:visible", "add-up-search"]);
watch(
  () => formVisible.value,
  val => {
    emit("update:visible", val);
  }
);

watch(
  () => props.visible,
  val => {
    formVisible.value = val;
  }
);

watch(
  () => props.data,
  val => {
    formData.value = val;
    if (formData.value.logo) {
      const filename = formData.value.logo.substring(
        formData.value.logo.lastIndexOf("/") + 1
      );
      fileList.value = [{ name: filename, url: formData.value.logo }];
    } else {
      fileList.value = [];
    }
  }
);

const rules = {
  title: [{ required: true, message: "请输入公告名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择类型", trigger: "blur" }],
  des: [{ required: true, message: "请输入描述简介", trigger: "blur" }],
  content: [{ required: true, message: "请输入公告内容", trigger: "blur" }],
  zt: [{ required: true, message: "请选择状态", trigger: "blur" }],
  noticetime: [{ required: true, message: "请输入发布时间", trigger: "blur" }],
  orderby: [{ required: true, message: "请输入排序顺序", trigger: "blur" }]
};

const mode = "default";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const toolbarConfig: any = { excludeKeys: "fullScreen" };
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file, insertFn) => {
        const form = new FormData();
        form.append("file", file);
        uploadImage(form)
          .then(res => {
            if (res.errno == 0) {
              message("上传成功", { type: "success" });
              insertFn(res.data.url, res.data.alt, res.data.href);
            } else {
              message("上传失败:" + res.message, { type: "error" });
            }
          })
          .catch(error => {
            message("上传失败:" + JSON.stringify(error), { type: "error" });
          });
      }
    },
    uploadVideo: {
      customUpload: async (file, insertFn) => {
        const form = new FormData();
        form.append("file", file);
        uploadVideo(form)
          .then(res => {
            if (res.errno == 0) {
              message("上传成功", { type: "success" });
              insertFn(res.data.url, res.data.poster);
            } else {
              message("上传失败:" + res.message, { type: "error" });
            }
          })
          .catch(error => {
            message("上传失败:" + JSON.stringify(error), { type: "error" });
          });
      }
    }
  }
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const beforeUpload = async file => {
  const form = new FormData();
  form.append("file", file);
  if (formData.value.type == 1) {
    uploadImage(form)
      .then(res => {
        if (res.errno == 0) {
          message("上传成功", { type: "success" });
          fileList.value = [{ name: res.data.alt, url: res.data.url }];
          formData.value.logo = res.data.url;
          return false;
        } else {
          message("上传失败:" + res.message, { type: "error" });
          return false;
        }
      })
      .catch(error => {
        message("上传失败:" + JSON.stringify(error), { type: "error" });
        return false;
      });
  } else {
    uploadVideo(form)
      .then(res => {
        if (res.errno == 0) {
          message("上传成功", { type: "success" });
          const filename = res.data.url.substring(
            res.data.url.lastIndexOf("/") + 1
          );
          fileList.value = [{ name: filename, url: res.data.url }];
          formData.value.logo = res.data.url;
          return false;
        } else {
          message("上传失败:" + res.message, { type: "error" });
          return false;
        }
      })
      .catch(error => {
        message("上传失败:" + JSON.stringify(error), { type: "error" });
        return false;
      });
  }
};

const beforeRemove = () => {
  fileList.value = [];
  formData.value.logo = "";
  return false;
};
</script>

<template>
  <el-dialog
    v-model="formVisible"
    title="编辑公告"
    :width="680"
    draggable
    :before-close="closeDialog"
  >
    <!-- 表单内容 -->
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="公告名称" prop="title">
        <el-input
          v-model="formData.title"
          :style="{ width: '480px' }"
          placeholder="请输入公告名称"
        />
      </el-form-item>
      <el-form-item label="发布类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio label="1">图文</el-radio>
          <el-radio label="2">视频</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="图片或视频" prop="logo">
        <el-upload
          action="upload"
          :before-upload="beforeUpload"
          :before-remove="beforeRemove"
          multiple
          :auto-upload="true"
          :file-list="fileList"
          :limit="1"
        >
          <el-button size="small" type="primary">上传文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述简介" prop="des">
        <el-input
          type="textarea"
          v-model="formData.des"
          :style="{ width: '480px' }"
          placeholder="请输入描述简介"
        />
      </el-form-item>
      <el-form-item label="公告内容" prop="content">
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
        />
        <Editor
          style="width: 100%; height: 400px; overflow-y: hidden"
          v-model="formData.content"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
        />
      </el-form-item>
      <el-form-item label="状态" prop="zt">
        <el-radio-group v-model="formData.zt">
          <el-radio label="0">待发布</el-radio>
          <el-radio label="1">已发布</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="发布时间" prop="noticetime">
        <el-date-picker
          v-model="formData.noticetime"
          type="date"
          placeholder="选择日期"
          format="YYYY 年 MM 月 DD 日"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="排序" prop="orderby">
        <el-input
          v-model="formData.orderby"
          :style="{ width: '480px' }"
          placeholder="请输入排序"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>
